package cn.com.taiji.oospub.wechat.common.tool;

import cn.com.taiji.oospub.wechat.common.CalendarValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;

import java.util.Calendar;

public class JsonTools {

	private static JsonConfig config;

	static {
		config = new JsonConfig();
//		config.addIgnoreFieldAnnotation(Transient.class);
		config.registerJsonValueProcessor(Calendar.class,
				new CalendarValueProcessor());
		config.registerDefaultValueProcessor(Boolean.class,
				new DefaultValueProcessor() {
					@Override
					@SuppressWarnings("rawtypes")
					public Object getDefaultValue(Class type) {
						return JSONNull.getInstance();
					}
				});
		//如果实体类中多对一关联中使用了延迟加载，则加上如下这个配置即可
		//config.setExcludes(new String[]{"handler","hibernateLazyInitializer"});
	}

	public static String toJSON(Object object, JsonConfig myConfig) {
		JSONObject result = JSONObject.fromObject(object, myConfig);
		return result.toString();
	}

	public static String toJSON(Object object) {
		return toJSON(object, config);
	}

	public static String toJSON(Object[] array) {
		JSONArray result = JSONArray.fromObject(array, config);
		return result.toString();
	}
	
	public static String toJSON(Object[] array , JsonConfig myConfig) {
		JSONArray result = JSONArray.fromObject(array, myConfig);
		return result.toString();
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T toBean(String jsonStr, Class<T> clazz , JsonConfig myConfig){
		JSONObject jsonObject = JSONObject.fromObject(jsonStr, myConfig);
		return  (T) JSONObject.toBean(jsonObject , clazz);
	}
	
	public static <T> T toBean(String jsonStr , Class<T> clazz){
		return toBean(jsonStr,clazz,config);
	}
	
	public static Object[] jsonToArray(String jsonStr, JsonConfig myConfig){
		JSONArray jsonArray = JSONArray.fromObject(jsonStr, myConfig);
		return jsonArray.toArray();
	}
	
	public static Object[] jsonToArray(String jsonStr){
		return jsonToArray(jsonStr , config);
	}

}
